package io.nutz.nutzsite.common.socket;

import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.plugins.mvc.websocket.AbstractWsEndpoint;
import org.nutz.plugins.mvc.websocket.NutWsConfigurator;
import org.nutz.plugins.mvc.websocket.WsHandler;

//ServerEndpoint是websocket的必备注解, value是映射路径, configurator是配置类.
@ServerEndpoint(value = "/websocket", configurator = NutWsConfigurator.class)
@IocBean(create = "init") // 使用NutWsConfigurator的必备条件
public class WkWebSocket extends AbstractWsEndpoint/* implements PubSub*/ {
    protected static final Log log = Logs.get();
    @Inject
    private Dao dao;
    /*@Inject
    protected PubSubService pubSubService;*/
    //@Inject
    //protected JedisAgent jedisAgent;
    @Inject("refer:$ioc")
    protected Ioc ioc;

    public WsHandler createHandler(Session session, EndpointConfig config) {
        return ioc.get(WkWsHandler.class);
    }

    public void init() {
        roomPrefix = "wsroom:";
        /*roomProvider = new WkJedisRoomProvider(jedisAgent);
        try (Jedis jedis = jedisAgent.getResource()) {
            for (String key : jedis.keys(roomPrefix + "*")) {
                switch (jedis.type(key)) {
                    case "none":
                        break;
                    case "set":
                        break;
//                    default:
//                        jedis.del(key);
                }
            }
        }
        pubSubService.reg(roomPrefix + "*", this);*/
    }


    public void onMessage(String channel, String message) {
        if (log.isDebugEnabled())
            log.debugf("GET PubSub channel=%s msg=%s", channel, message);
        each(channel, (index, session, length) -> session.getAsyncRemote().sendText(message));
    }
    @Override
    public void onMesssageString(Session session, String msg) {
        super.onMesssageString(session, msg);

        Logs.get().info("onMessageString, msg: " + msg + ", mSession: " + session);
    }
    @Override
    public void onOpen(Session session, EndpointConfig config) {
        this.changeSessionId(session);
        String wsid = session.getId();
        WsHandler handler = this.createHandler(session, config);
        handler.setRoomProvider(this.roomProvider);
        handler.setSession(session);
        handler.setEndpoint(this);
        handler.init();
        try{
            session.addMessageHandler(handler);
        }catch (Exception e){
            log.debug(e);
        }

        this.sessions.put(wsid, session);
        this.handlers.put(wsid, handler);
    }
}
